package leetcode;

import java.util.Map;

public class _8_StringToInteger {
    class Solution {
        public int myAtoi(String str) {
            String snum = "0123456789";
            Integer[] num = {0,1,2,3,4,5,6,7,8,9};
            int min_border = (int)Math.pow(-2,31);
            int max_border =(int) (Math.pow(2,31)-1);
            String str2 = str.trim();
            if (str2.length() == 0 || (str2.charAt(0) != '-' && str2.charAt(0) != '+' && !snum.contains(String.valueOf(str2.charAt(0))))) {
                return 0;
            }
            double res = 0;
            int index = 0;
            if (str2.charAt(0) == '-'){
                index++;
                while (index < str2.length() && snum.contains(String.valueOf(str2.charAt(index)))){
                    res *= 10;
                    res += num[snum.indexOf(str2.charAt(index))];
                    index++;
                }
                res = 0-res;
                if (res < min_border){
                    return min_border;
                }
            }
            else {
                if (str2.charAt(0) == '+') index++;
                while (index < str2.length() && snum.contains(String.valueOf(str2.charAt(index)))){
                    res *= 10;
                    res += num[snum.indexOf(str2.charAt(index))];
                    index++;
                }
                if (res > max_border){
                    return (max_border);
                }
            }
            return (int)res;
        }
    }

    Solution getSolution(){
        return new Solution();
    }

    public static void main(String[] args){
        _8_StringToInteger c = new _8_StringToInteger();
        _8_StringToInteger.Solution  s  = c.getSolution();
        String str = "2147483647";
        int res = s.myAtoi(str);
        System.out.println(res);
    }
}
